//
//  PlSInjector_VersionCheck.m
//  Injector
//
//  Created by ∞ on 19/12/07.
//  Copyright 2007 Emanuele Vulcano (infinite-labs.net). All rights reserved.
//

#import "PlSInjector_VersionCheck.h"
#import "NSAlert+L0Alert.h"
#import "PlSManager.h"

@implementation PlSInjector (VersionCheck)

- (void) checkForUpdates {
	NSDate* date = [self.preferences lastUpdateCheckDate];
//	if (date && (-[date timeIntervalSinceNow]) > 604800) { // one week
	if (YES) {
		self.updateUI.activateBeforeShowingAlerts = YES;
		self.updateUI.displayNoticeIfNoUpdate = NO;
		if (self.preferences.checkForPlugSuitUpdates)
			[self beginUpdatingApplication];
		else if (self.preferences.checkForPlugInUpdates)
			[self beginUpdatingPlugIns];
		
		
		[self.preferences markNowAsLastUpdateCheckDate];
	} else if (!date)
		[self.preferences markNowAsLastUpdateCheckDate];
}

- (void) beginUpdatingPlugIns {
	NSMutableArray* plugIns = [NSMutableArray array];
	for (PlSManager* mgr in self.managers) {
		[mgr rescan];
		[plugIns addObjectsFromArray:mgr.plugIns];
	}
	
	NSEnumerator* enu = [plugIns objectEnumerator];
	NSArray* objs = [[NSArray arrayWithObjects:plugIns, enu, nil] retain];
	
	PlSPlugIn* pin = [enu nextObject];
	
	if (pin)
		[self.updateUI beginCheckForUpdateForPlugIn:pin modalForWindow:nil delegate:self didEndSelector:@selector(_updateUI:plugInUpdated:context:) context:(void*) objs];
}

- (void) beginUpdatingApplication {
	[self.updateUI beginCheckForAppUpdateModalForWindow:nil delegate:self didEndSelector:@selector(_updateUI:appUpdated:context:) context:nil];
}

- (void) _updateUI:(PlSUpdateUI*) ui appUpdated:(PlSUpdateResult) result context:(void*) nothing {
	
	if (self.preferences.checkForPlugInUpdates)
		[self beginUpdatingPlugIns];
}

- (void) _updateUI:(PlSUpdateUI*) ui plugInUpdated:(PlSUpdateResult) result context:(void*) objs {
	NSEnumerator* enu = [(id)objs objectAtIndex:1];
	
	PlSPlugIn* pin = [enu nextObject];
	if (pin)
		[self.updateUI beginCheckForUpdateForPlugIn:pin modalForWindow:nil delegate:self didEndSelector:@selector(_updateUI:plugInUpdated:context:) context:objs];
	else
		[(id)objs release];
}

@end
